package com.sykj.weichat.web;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.Gson;
import com.sykj.weichat.model.BisCustomUser;
import com.sykj.weichat.model.BisSmsRecord;
import com.sykj.util.HttpsUtils;
import com.sykj.util.JavaSmsApi1;
import com.sykj.util.WeichatToken;
import com.sykj.weichat.service.BisCustomUserService;
import com.sykj.weichat.service.BisSmsRecordService;

/**
 * 
 * 类名:com.sykj.weichat.web.WechatLoginController
 * 描述:
 * @author 张孝柱
 * 创建时间:2018年9月6日 
 * 修改说明:
 */
@Controller
@RequestMapping("/weichat")
public class WeichatLoginController {
	/**
	 * 通过网页授权获取用户信息
	 */
	public static final String  OAUTH2__URER_URL="https://api.weixin.qq.com/sns/userinfo";
	/**
	 * 微信网页授权路径
	 */ 
	public static final String OAUTH2_URL = "https://open.weixin.qq.com/connect/oauth2/authorize";
	public static final String TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token";
	/**
	 * appID
	 */ 
	 public static final String appid = "wx5fcf6284ca955e5f";
	   /**
	    * 授权方法
	    */
	   @RequestMapping("/login")
		public void  auth2Weichat( HttpServletResponse response){
			Map<String, Object> map = new HashMap<>();
			map.put("appid", appid);
			map.put("redirect_uri", "http://5ef6dfd7.ngrok.io/weichat/initlogin");//自己的登录路径
			map.put("response_type", "code");
			map.put("scope", "snsapi_userinfo");
			map.put("state", "STATE#wechat_redirect");
			//String sendByHttp = HttpsUtils.sendByHttp(map, url);
			//System.out.println("sendByHttp="+sendByHttp);
			System.out.println("-*/-*-*-*-/*-/-" + OAUTH2_URL+toParams(map));
			try {
				response.sendRedirect(OAUTH2_URL+toParams(map));
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
	 
	   /**
	    * 组装请求参数
	    * @param map
	    * @return
	    */
	    public static String toParams(Map<String, Object> map){
	    Set keyset = map.keySet();
	    StringBuilder sb = new StringBuilder("?");
	    	for (Iterator i = keyset.iterator();i.hasNext();) {
				String key = (String) i.next();
				sb.append(key).append("=");
				sb.append(map.get(key));
				if (i.hasNext()) {
					sb.append("&");
				}
			}
			return sb.toString();
	    	
	    }
	 @Autowired
	 BisCustomUserService BisCustomUserService;
	 @Autowired
	 BisSmsRecordService BisSmsRecordService;
	 @RequestMapping("/initlogin")
		public ModelAndView login(String code, HttpServletResponse response, HttpServletRequest request,BisCustomUser bisCustomUser) throws IOException {
		 System.out.println("================="+code + ", address="+request.getRemoteAddr());
		 ModelAndView view = new ModelAndView();
		 if (code!=null) {
			 Map<String, Object> map = new HashMap<>();
				map.put("appid", appid);
				map.put("secret", "871e517792e439d68a394abfdb95692a");
				map.put("code", code);
				map.put("grant_type", "authorization_code");
				String sendByHttp = HttpsUtils.sendByHttp(map, TOKEN_URL);
				System.out.println("-*-*"+sendByHttp);
					Gson gson = new Gson();
					WeichatToken result = gson.fromJson(sendByHttp, WeichatToken.class);

					System.out.println("sendByHttp="+sendByHttp);
					if (result!=null) {
						//获取用户信息
						getUserinfo(result,request);
						BisCustomUser getopenid = BisCustomUserService.getopenid(result.getOpenid());
						view.addObject("customUserPO", getopenid);
						
					}
					
		}

			view.setViewName("weichat/wechatLogin.jsp");
			return view;
		}
	 
	    public void getUserinfo(WeichatToken result,HttpServletRequest request) throws IOException{
	    	Map<String, Object> map = new HashMap<>();
			map.put("access_token", result.getAccess_token());
			map.put("openid", result.getOpenid());
			map.put("lang", "zh_CN");
			String sendByHttp = HttpsUtils.sendByHttp(map, OAUTH2__URER_URL);
			Gson gson = new Gson();
			System.out.println("======"+sendByHttp);
			Map<String, Object> result1 = gson.fromJson(sendByHttp, HashMap.class);
			//BisCustomUser bisCustomUser = new BisCustomUser();
			String openid = (String) result1.get("openid");
			String nickname = (String) result1.get("nickname");
			double sex = (double) result1.get("sex");
			String city = (String) result1.get("city");
			String headimgurl = (String) result1.get("headimgurl");
			String userPhoto = getUserPhoto(headimgurl,request);
			System.out.println("-*-*-*-*-*-*"+userPhoto);
			BisCustomUser bisCustomUser = BisCustomUserService.getopenid(openid);
			System.out.println();
			//如果用户表里没有该openid用户，添加一个新用户
			if (bisCustomUser==null) {
				bisCustomUser = new BisCustomUser();
		        BisCustomUser maxid = BisCustomUserService.maxid(bisCustomUser);
		        String custom_user_id = maxid.getCustom_user_id();
				bisCustomUser.setOpenid(openid);
				bisCustomUser.setCustom_user_id(custom_user_id);
				bisCustomUser.setNikename(nickname);
				bisCustomUser.setUsername(nickname);
				bisCustomUser.setPhoto(userPhoto);
				if (sex==1){
					bisCustomUser.setSex("男");
				}else if (sex==2) {
					bisCustomUser.setSex("女");
				}
				bisCustomUser.setAddress(city);
				BisCustomUserService.register(bisCustomUser);//添加用户信息
			} else {//否则修改该用户的信息
				bisCustomUser.setNikename(nickname);
				bisCustomUser.setUsername(nickname);
				bisCustomUser.setPhoto(userPhoto);
				if (sex==1){
					bisCustomUser.setSex("男");
				}else if (sex==2) {
					bisCustomUser.setSex("女");
				}
				bisCustomUser.setAddress(city);
				BisCustomUserService.update(bisCustomUser); //修改用户信息
			}
	    }
	    
	    private String getUserPhoto(String url,HttpServletRequest request) throws IOException {
	    	String path = request.getRealPath("/static/images/");
	    	 String fileName = System.currentTimeMillis()+".png";
            File file = new File(path+"/"+fileName);
            if (!file.exists()) {
            	file.createNewFile();
            }
	    	HttpsUtils.downloadPicture(url,file);
	    	String returnPath = "/static/images/" + fileName;
			return returnPath;
		}
	    
		@RequestMapping("/login/getall")
		@ResponseBody
		public String getall(String mobile,String checkCode,String openid,Model model,HttpSession session,BisCustomUser bisCustomUser) {
			session.setAttribute("openid", openid);
			System.out.println("****"+openid);
			String result = "{\"appcode\":\"%s\", \"appmsg\":\"%s\" }";
			BisSmsRecord code = BisSmsRecordService.code(mobile);
			
			System.out.println("code.getContent()="+code.getContent()+", checkCode="+checkCode);
			if (code.getContent().equals(checkCode)) {
				/*BisCustomUser getall = BisCustomUserService.getall(mobile);
				if (getall!=null) {
					
					model.addAttribute("1", getall);
					result = String.format(result,"1", "登录成功!");
				} else {
					result = String.format(result,"0", "登录失败!");
				}*/
				BisCustomUser getopenid = BisCustomUserService.getopenid(openid);
				session.setAttribute("mobile", mobile);
				session.setAttribute("custom_user_id", getopenid.getCustom_user_id());
				if (getopenid!=null) {
					bisCustomUser.setCustom_user_id(getopenid.getCustom_user_id());
					bisCustomUser.setMobile(mobile);
					BisCustomUserService.mobile(bisCustomUser);
					result = String.format(result,"1", "登录成功!");
				} else {
					result = String.format(result,"0", "没有微信授权!");
				}
			}else {
				result = String.format(result,"0", "验证码错误!");
			}
			
			return result;
		}
		/**
		 * 
		 * 简要说明：发送手机验证码
		 * 编写者：陈骑元
		 * 创建时间：2017年5月21日 上午12:52:42
		 * @param 说明
		 * @return 说明
		 */
		@RequestMapping("/login/sendCheckCode")
		@ResponseBody
		public String sendCheckCode(String mobile,BisSmsRecord bisSmsRecord,Model model,HttpSession session){
			String result = "{\"appcode\":\"%s\", \"appmsg\":\"%s\" }";
			JavaSmsApi1 j = new JavaSmsApi1();
			
			try {
				String randomCode = j.randomCode();
				System.out.println("*/-"+randomCode);
				String sendSms = j.sendSms(mobile,randomCode);
				bisSmsRecord.setContent(randomCode);
				String replace = UUID.randomUUID().toString().replace("-", "");
				bisSmsRecord.setRecord_id(replace);
				bisSmsRecord.setMobile(mobile);
				bisSmsRecord.setCreate_time(new Date());
				bisSmsRecord.setSend_time(new Date());
				Gson gson = new Gson();
				Map<String, Object> map = gson.fromJson(sendSms, HashMap.class);
				if (map.get("respCode").equals("00000")) {
					bisSmsRecord.setStatus("1");
					BisSmsRecordService.insert(bisSmsRecord);
					result = String.format(result,"1", "发送验证码成功!");
				}else {
					bisSmsRecord.setStatus("2");
					String object = (String) map.get("respDesc");
					bisSmsRecord.setFailure_cause(object);
					BisSmsRecordService.insert(bisSmsRecord);
					result = String.format(result,"0", object);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return result;
		}
		
}
